package day11.reflect2;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Before;
import org.junit.Test;

public class Demo4 {
	
	Class<?> class1 ;
	
	//每次运行@Test方法前会先执行有@Before的方法
	@Before
	public void before() {
		class1 = Student.class;
	}
	
	//通过反射获取方法对象
	@Test
	public void test() {
		Method[] methods = class1.getMethods();
		System.out.println("methods.length:" + methods.length);
		for (Method method : methods) {
			System.out.println(method);
		}
	}
	
	//获取所有的方法
	@Test
	public void test2() {
		Method[] methods = class1.getDeclaredMethods();
		System.out.println("methods.length:" + methods.length);
		for (Method method : methods) {
			System.out.println(method);
		}
	}
	
	//获取指定的静态方法 不需要对象调用的，是由类名调用
	@Test
	public void test3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Method method = class1.getDeclaredMethod("study");
		//调用方法 null:不需要传对象
		method.invoke(null);
	}
	
	//获取指定的静态私有方法 不需要对象调用的，是由类名调用
	@Test
	public void test4() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Method method = class1.getDeclaredMethod("studyX");
		
		//修改访问权限
		method.setAccessible(true);
		//调用方法 null:不需要传对象
		method.invoke(null);
	}
	
	//先获取实例方法 ，创建对象，再调用
	@Test
	public void test5() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
		Method method = class1.getDeclaredMethod("eat");
		
		//创建对象  class1.newInstance() => new Student();
		Student stu = (Student) class1.newInstance();
		
		//stu.eat();
		method.invoke(stu);
	}
	
	@Test
	public void test6() throws Exception {
		//public void sleep(int hour){
		Method method = class1.getDeclaredMethod("sleep",int.class);
		
		//创建对象  class1.newInstance() => new Student();
		Student stu = (Student) class1.newInstance();
		
		//stu.sleep(7);
		method.invoke(stu,7);
	}
	
	//私有的，实例方法   private void show()
	@Test
	public void test7() throws Exception {
		//public void sleep(int hour){
		Method method = class1.getDeclaredMethod("show");
		
		//设置方法可以访问 
		method.setAccessible(true);
		
		//创建对象  class1.newInstance() => new Student();
		Student stu = (Student) class1.newInstance();
		
		//stu.show();
		method.invoke(stu);
	}
}
